package com.kobeliu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.mapper.ChatMessageMapper;
import com.kobeliu.pojo.ChatMessage;
import com.kobeliu.pojo.netty.ChatMsg;
import com.kobeliu.service.ChatMessageService;
import com.kobeliu.utils.PagedGridResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ChatMessageServiceImpl extends BaseInfoProperties implements ChatMessageService {


    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Transactional
    @Override
    public void saveMessage(ChatMsg chatMsg) {

        ChatMessage pending = new ChatMessage();

        BeanUtils.copyProperties(chatMsg,pending);
        //不使用自动生成
        //因为异步，所以如果自动生成，接收方拿不到这个id
        //所以我们在netty server生成一个Id带到消费端这里
        pending.setId(chatMsg.getMsgId());

        chatMessageMapper.insert(pending);

        //redis中increment
        //一个receiver可能跟多人聊天 所以我们要键值对，便于单个人的统计与总数统计
        redis.incrementHash(CHAT_MSG_LIST+":"+pending.getReceiverId(),pending.getSenderId(),1);


    }

    @Override
    public Map getMyUnreadCounts(String myId) {

        // hash查找
        Map map = redis.hgetall(CHAT_MSG_LIST + ":" + myId);
        return map;
    }

    @Override
    public void clearMyUnReadCounts(String myId, String oppositeId) {
        redis.setHashValue(CHAT_MSG_LIST + ":" + myId,oppositeId,"0");
    }

    @Override
    public PagedGridResult pagedChatMsg(String userId, String oppositeId, Integer page, Integer pageSize) {

        PageHelper.startPage(page,pageSize);

        List<ChatMessage> msgList = chatMessageMapper
                .selectList(new QueryWrapper<ChatMessage>()
                        .or(qw -> qw.eq("sender_id",userId)
                        .eq("receiver_id",oppositeId))
                        //双向都要获取
                        .or(qw -> qw.eq("sender_id",oppositeId)
                                .eq("receiver_id",userId))
                .orderByDesc("chat_time"));

        //拿到list,要进行重排序

        PagedGridResult result = setterPagedGrid(msgList,page);
        List<ChatMessage> newList = msgList.stream().sorted(Comparator.comparing(ChatMessage::getChatTime)).collect(Collectors.toList());
        result.setRows(newList);

        return result;

    }

    @Transactional
    @Override
    public void updateMsgSignRead(String msgId) {


        ChatMessage pending = new ChatMessage();
        pending.setId(msgId);
        pending.setIsRead(true);
        chatMessageMapper.updateById(pending);
    }



}
